<?php

class ClientAdmin extends AppModel
{

	public $name = 'ClientAdmin';

	public $displayField = 'username';

	public $statuses = array(
        'ACTIVE',
        'INACTIVE',
	);

	public $permissions = array(
        'CANDIDATES',
            // Администрирование базы данных пользователей,
            // назначение тестов, администрирование тестов, внесению результатов тестирования с бланка.
        'EMAIL_ON_TEST',
            // Получение e-mail о прохождении теста пользователем.
        'REPORTS',
            // Генерирование и просмотр отчётов.
        'EMAIL_ON_REPORT',
            // Генерирование отчётов и получение сгенерированных данным Клиент-администратором отчётов по e-mail.
        'ARCHIVE',
            // Просмотр архива информации о пользователях.
	);

	public $validate = array(
        'name' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'first0' => array(
                'rule' => array('maxLength', 255),
                'message' => 'too long',
            ),
        ),
        'status' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'first0' => array(
                'rule' => array('allowStatus'),
                'message' => 'invalid_value',
            ),
        ),
        'username' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'second_1' => array(
                'rule' => array('lengthBetween', 3, 15),
                'message' => 'ClientAdmin.username.length',
            ),
            'second_2' => array(
                'rule' => array('customEreg', '^[0-9a-zA-Z_]([’.-–—]?([0-9a-zA-Z_]))*$'),
                'message' => 'ClientAdmin.username.invalid',
            ),
            'third' => array(
                'rule' => array('allowUserName'),
                'message' => 'ClientAdmin.username.exists',
            ),
        ),
		/*'password' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'first' => array(
                'rule' => array('lengthBetween', 6, 20),
                'message' => 'password.length',
            ),
            'second_1' => array(
             	'rule' => array('customEreg', '[[:upper:]]'),
                'message' => 'password.invalid',
            ),
            'second_2' => array(
             	'rule' => array('customEreg', '[[:lower:]]'),
                'message' => 'password.invalid',
            ),
            'second_3' => array(
             	'rule' => array('customEreg', '[[:digit:]]'),
                'message' => 'password.invalid',
            ),
        ),*/
		/*'confirm_password' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'password.confirm',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'password.confirm',
            ),
            'first' => array(
                'rule' => array('equalWith', 'password'),
                'message' => 'password.confirm',
            ),
        ),*/
		'email' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'first0' => array(
                'rule' => array('maxLength', 100),
                'message' => 'too long',
            ),
            'first' => array(
                'rule' => array('email', false),
                'message' => 'email',
            ),
        ),
		'permissions' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => true,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => true,
                'message' => 'required',
            ),
        'first' => array(
                'rule' => array('allowPermissions'),
                'message' => 'invalid_value',
            ),
        ),
		'client_id' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'first' => array(
                'rule' => array('allowClient', false),
                'message' => 'invalid_value',
            ),
        ),
	);

	public $belongsTo = array(
		'Client' => array('className' => 'Client'),
	);

    function allowUserName($data)
    {
        $otherModel =& $this->getModel('Admin');
        $otherModel->rel();
        $this->rel();
		return ! is_array($otherModel->find(array("`username`" => $data)))
		&&
        ! is_array($this->find(array("`{$this->primaryKey}`" => "!=".intval($this->id), "`username`" => $data)));
    }

    function allowEmail($data)
    {
        $this->rel();
        return ! is_array($this->find(array("`{$this->primaryKey}`" => "!=".intval($this->id), "`email`" => $data)));
    }

    function allowClient($data)
    {
        $this->rel();
        return is_array($this->Client->find(array("`{$this->Client->primaryKey}`" => $data)));
    }

	function beforeValidate()
	{
	    if (isset($this->data[$this->name]) && is_array($this->data[$this->name])) {
    	    if (array_key_exists('password', $this->data[$this->name])) {
        	    $pass_length = mb_strlen($this->data[$this->name]['password']);
        	    if (!$pass_length || $pass_length==32) {
        	        unset($this->data[$this->name]['password']);
        	    }
            }
            if (!array_key_exists('password', $this->data[$this->name]) && array_key_exists('confirm_password', $this->data[$this->name])) {
    	        unset($this->data[$this->name]['confirm_password']);
            }
	    }
	    return true;
	}

	function beforeSave()
	{
	    $creating = ! $this->exists();

	    if (array_key_exists('permissions', $this->data[$this->name]) && is_array($this->data[$this->name]['permissions'])) {
	    	$this->data[$this->name]['permissions'] = '';
	    }

	    if ($creating) {
            $this->data[$this->name]['created'] = date('Y-m-d H:i:s');
	    }
	    // пароль хранится в открытом виде
        /*if (array_key_exists('password', $this->data[$this->name])) {
            $this->data[$this->name]['password'] = md5($this->data[$this->name]['password']);
        }*/
	    return parent::beforeSave();
	}

	function getStatuses()
	{
	    return $this->statuses;
	}

	function getStatusesList()
	{
	    $result = array();
	    foreach ($this->statuses as $type) {
	        $result[$type] = __d('client_admins', 'status_'.$type, true);
	    }
	    return $result;
	}

	function allowPermissions($data)
	{
	    $allow = !(bool)count(array_diff($data, array_values($this->permissions)));
	    if ($allow) {
            $this->data[$this->name]['permissions'] = implode(',', $data);
	        return true;
	    }
        return false;
	}

	function allowStatus($data)
	{
        return in_array($data, $this->statuses);
	}

	function getPermissions()
	{
		$count = 0;

		$result = array();
		foreach ($this->permissions as $perm) {
			if (++$count > 64) {
				break;
			}
			$result[pow(2, ($count - 1))] = $perm;
		}
	    return $result;
	}

	function getPermissionsList()
	{
	    $result = array();
	    foreach ($this->permissions as $perm) {
	        $result[$perm] = __d('client_admins', 'permission_'.$perm, true);
	    }
	    return $result;
	}

	function &searcheUser($username, $password)
	{
	    $data = null;
	    $id = null;
        $model =& $this->getModel('Admin');
        $model->rel();
        if ($tmp = $model->find(array('username'=>$username, 'password'=>md5($password)), array($model->primaryKey, 'username', 'status'))) {
            $id = $tmp[$model->name][$model->primaryKey] * 2;
            unset($tmp[$model->name][$model->primaryKey]);
            $data = $tmp[$model->name];
            $data['type'] = 'admin';
        } else {
            $model =& $this->getModel('ClientAdmin');
            $model->rel();
            if ($tmp = $model->find(array('username'=>$username, 'password'=>$password), array($model->primaryKey, 'username', 'email', 'status', 'permissions'))) {

                $id = $tmp[$model->name][$model->primaryKey] * 2 + 1;
                unset($tmp[$model->name][$model->primaryKey]);
                $data = $tmp[$model->name];
                $data['type'] = 'client_admin';
            } else {
                $null = null;
                return $null;
            }
        }

        $res = new _User($id, $data);
        return $res;
	}

	function &getUser($id)
	{
	    $data = null;
	    if (($id % 2) === 0) {
            $model =& $this->getModel('Admin');
            $model->rel();
            if ($tmp = $model->read(array($model->primaryKey, 'username', 'status'), $id/2)) {
                $id = $tmp[$model->name][$model->primaryKey] * 2;
                unset($tmp[$model->name][$model->primaryKey]);
                $data = $tmp[$model->name];
	            $data['type'] = 'admin';
            } else {
                $null = null;
                return $null;
            }
	    } else {
            $model =& $this->getModel('ClientAdmin');
            $model->rel();
            if ($tmp = $model->read(array($model->primaryKey, 'username', 'status', 'email', 'permissions', 'client_id'), ($id-1)/2)) {
                $id = $tmp[$model->name][$model->primaryKey] * 2 + 1;
                unset($tmp[$model->name][$model->primaryKey]);
                $data = $tmp[$model->name];
                $data['type'] = 'client_admin';
            } else {
                $null = null;
                return $null;
            }
	    }

        $res = new _User($id, $data);
        return $res;
	}

	function allowDelete($fields = null)
	{
        return false;
	}

	function allowUpdate($fields = null)
	{
        return Auth::o()->is('admin');
	}

	function modifyRow(&$row, $primary)
	{
        if (is_array($row) && array_key_exists('permissions', $row)) {
    	    if (strlen($row['permissions'])) {
                $row['permissions'] = explode(',', $row['permissions']);
        	} else {
                $row['permissions'] = array();
        	}
        }
	}

	function getRecepientsReportEmails($client_id)
	{
		$result = array();

		$permission_id = array_keys($this->getPermissions(), 'EMAIL_ON_REPORT', true);
		if (empty($permission_id[0])) {
			return array();
		}
		$permission_id = $permission_id[0];

		$conds = array();
		$conds[]["`{$this->name}`.`client_id`"] = $client_id;
		$conds[] = "`{$this->name}`.`permissions` & {$permission_id}";
		$result = $this->findAll($conds);
		if (empty($result)) {
			$result = array();
		}

		return $result;
	}

	function getRecepientsTestEmails($client_id)
	{
		$result = array();

		$permission_id = array_keys($this->getPermissions(), 'EMAIL_ON_TEST', true);
		if (empty($permission_id[0])) {
			return array();
		}
		$permission_id = $permission_id[0];

		$conds = array();
		$conds[]["`{$this->name}`.`client_id`"] = $client_id;
		$conds[] = "`{$this->name}`.`permissions` & {$permission_id}";
		$result = $this->findAll($conds);
		if (empty($result)) {
			$result = array();
		}

		return $result;
	}
}

?>